﻿using Help;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLLA
{
    public partial class Order_MerPricing_T : BaseBLL<Model.Order_MerPricing_T>, IBLL.IOrder_MerPricing_TBLL
    {
        ObjectSerialize os = new ObjectSerialize();
        DataResult result = new DataResult();
        IBLL.IBLLSession bl = DI.SpringHelper.GetObject<IBLL.IBLLSession>("BLLSession");

        /// <summary>
        /// 查询所有商户的订单优惠信息
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页面大小</param>
        /// <param name="MerID">商户ID</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式(1:json;2:xml)</param>
        /// <returns></returns>
        public string GetOrder_MerPricing(int pageIndex, int pageSize, string MerID, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 业务层
            try
            {
                List<Model.View_Order_MerPricing> ls = base.DBSession.IView_Order_MerPricingDAL.GetListBy("SELECT*  FROM  View_Order_MerPricing where MerID='" + MerID + "' and PricState=1");
                if (ls != null && ls.Count > 0)
                {
                    List<View_Order_MerPricing_More> list = new List<View_Order_MerPricing_More>();
                    // 判断支付模式，获取对应的支付名称
                    foreach (Model.View_Order_MerPricing item in ls)
                    {
                        #region
                        View_Order_MerPricing_More info = new View_Order_MerPricing_More();
                        if (item.IsFirstMon != null)
                        {
                            info.IsFirstMon = item.IsFirstMon;
                        }
                        if (item.IsFormMon != null)
                        {
                            info.IsFormMon = item.IsFormMon;
                        }
                        if (item.IsMaxPric != null)
                        {
                            info.IsMaxPric = item.IsMaxPric;
                        }
                        if (item.IsOpen != null)
                        {
                            info.IsOpen = item.IsOpen;
                        }
                        if (item.IsPackMon != null)
                        {
                            info.IsPackMon = item.IsPackMon;
                        }
                        if (item.MerID != null)
                        {
                            info.MerID = item.MerID;
                        }
                        if (item.MerName != null)
                        {
                            info.MerName = item.MerName;
                        }
                        if (item.MonType != null)
                        {
                            info.MonType = item.MonType;
                        }
                        if (item.PayID != null)
                        {
                            info.PayID = item.PayID;
                        }
                        if (item.PricID != null)
                        {
                            info.PricID = item.PricID;
                        }
                        if (item.PricMon != null)
                        {
                            info.PricMon = item.PricMon;
                        }
                        if (item.PricRem != null)
                        {
                            info.PricRem = item.PricRem;
                        }
                        if (item.PricState != null)
                        {
                            info.PricState = item.PricState;
                        }
                        if (item.PricTxt != null)
                        {
                            info.PricTxt = item.PricTxt;
                        }
                        if (item.PricType != null)
                        {
                            info.PricType = item.PricType;
                        }
                        #endregion
                        if (item.PricType == 0)
                        {
                            List<Model.Order_Walt_T> list_tmp = bl.IOrder_Walt_TBLL.GetListBy(u => u.WaltID == item.PayID);
                            if (list_tmp != null && list_tmp.Count > 0)
                            {
                                info.PayName = list_tmp.First().WaltName;
                            }
                        }
                        else if (item.PricType == 1)
                        {
                            List<Model.Order_Pay_T> list_tmp = bl.IOrder_Pay_TBLL.GetListBy(u => u.PayID == item.PayID);
                            if (list_tmp != null && list_tmp.Count > 0)
                            {
                                info.PayName = list_tmp.First().PayName;
                            }
                        }
                        list.Add(info);
                    }

                    result.BS = "1";
                    result.Msg = "查询成功";
                    result.rows = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                    result.total = list.Count;
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "查询不到数据";
                }
                return os.StringOfObject(result, RETID);
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("查询所有商户的订单优惠信息失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "系统错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
        }

        #region    找一个订单里有多个优惠
        /// <summary>
        /// 找一个订单里有多少个优惠
        /// </summary>
        /// <param name="MerID">商户ID</param>
        /// <param name="PayID">钱包ID</param>
        /// <param name="PricType">钱包类型（0：钱包，1：第三方）</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式(1:json;2:xml)</param>
        /// <returns></returns>
        public string GetDiscounts(string MerID, string PayID, int PricType, string YZM, int RETID)
        {
            try
            {
                #region 匹配验证码
                if (YZM != Help.ALL_DataV.YZM)
                {
                    result.BS = "-88";
                    result.Msg = "验证码错误！";
                    return os.StringOfObject(result, RETID);
                }
                #endregion
                if (string.IsNullOrEmpty(PayID))
                {
                    result.BS = "-1";
                    result.Msg = "找不到支付模式";
                    return os.StringOfObject(result, RETID);
                }

                List<Model.Order_MerPricing_T> pricList = base.DBSession.IOrder_MerPricing_TDAL.GetListBy(u => u.MerID == MerID & u.PayID == PayID & u.PricType == PricType & u.PricState == 1);
                if (pricList.Count <= 0)
                {
                    result.BS = "0";
                    result.Msg = "这里没有优惠";
                    return os.StringOfObject(result, RETID);
                }

                result.BS = "1";
                result.Msg = "找到优惠了";
                result.total = pricList.Count;
                result.rows = pricList;
                return os.StringOfObject(result, RETID);
            }
            catch (Exception e)
            {
                result.BS = "-99";
                result.Msg = "系统异常";
                WriteLog.WriteW("GetDiscounts(\"" + MerID + "\",\"" + PayID + "\"," + PricType + ",\"" + YZM + "\"," + RETID + ")            " + e.Message);
                return os.StringOfObject(result, RETID);
            }
        }
        #endregion

        #region  计算用户选择的优惠
        /// <summary>
        /// 
        /// </summary>
        /// <param name="DishIDs">菜品ID集合</param>
        /// <param name="DistCount">菜品数量集合</param>
        /// <param name="MerID">商户ID</param>
        /// <param name="PricID">钱包ID</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public string CalcDiscount(string[] DishIDs, int[] DistCount, string MerID, string PricID, int IsTake, string YZM, int RETID)
        {
            try
            {
                #region 匹配验证码
                if (YZM != Help.ALL_DataV.YZM)
                {
                    result.BS = "-88";
                    result.Msg = "验证码错误！";
                    return os.StringOfObject(result, RETID);
                }
                #endregion

                Model.OrderTotal OT = new OrderTotal();
                double i_优惠后总价 = 0, i_总价 = 0;
                List<string> DishIDsList = new List<string>();
                List<int> DistCountList = new List<int>();


                for (int i = 0; i < DistCount.Length; i++)
                {
                    if (DistCount[i] != 0)
                    {
                        DishIDsList.Add(DishIDs[i]);
                        DistCountList.Add(DistCount[i]);
                    }
                }

                List<Model.Order_Dishes_T> Dist = base.DBSession.IOrder_Dishes_TDAL.GetListBy(u => DishIDsList.Contains(u.DishesID));
                int[] dic = new int[DistCountList.Count];
                for (int i = 0; i < DistCountList.Count; i++)
                {
                    dic[i] = DistCountList[i];
                }
                OT.DishList = Dist;
                OT.CountArr = dic;

                double i_商品总价 = 0, i_打包费总价 = 0, i_消费积分 = 0,i_订餐份数=0; 
                for (int i = 0; i < Dist.Count; i++)
                {
                    if (Dist[i].DishesIsInt == 0)
                    {
                        i_订餐份数 += dic[i];
                        i_商品总价 += Dist[i].DishesPay * dic[i];
                        i_打包费总价 += Dist[i].DelPackMon * dic[i];
                    }
                    else
                    {
                        i_订餐份数 +=  dic[i];
                        i_消费积分 += Dist[i].DishesPay * dic[i];
                        i_打包费总价 += Dist[i].DelPackMon * dic[i];
                    }
                }
                Model.Order_Mer_T Mer = base.DBSession.IOrder_Mer_TDAL.GetListBy(u => u.MerID == MerID).First();
                i_总价 = i_商品总价 + i_打包费总价;
                int i_派送费更多 = 0;
                if (Mer.Greater > 0 & i_订餐份数>Mer.Greater)
                {
                    int djfs = (int)i_订餐份数 - Mer.Greater;
                    double fs = djfs / Mer.HowCount;
                    if (fs == 0) fs = 1;
                    i_派送费更多 = (int)fs * Mer.AddMoney;
                }
                i_总价 += Mer.DelFormMon + i_派送费更多;
                i_优惠后总价 = i_总价;
                OT.TotalPoint = i_消费积分.ToString();
                OT.DelFormMon = Mer.DelFormMon + i_派送费更多;
                OT.DelMonTxt = Mer.DelMonTxt;
                if (!string.IsNullOrWhiteSpace(PricID))
                {
                    try
                    {
                        double d_可算优惠金额 = i_总价;
                        Model.Order_MerPricing_T MerPrin = base.DBSession.IOrder_MerPricing_TDAL.GetListBy(u => u.PayID == PricID & u.PricState == 1 & u.MerID == MerID).First();

                        if (MerPrin.IsFormMon == 0)
                        {
                            d_可算优惠金额 -= Mer.DelFormMon;
                        }
                        if (MerPrin.IsPackMon == 0)
                        {
                            d_可算优惠金额 -= i_打包费总价;
                        }
                        d_可算优惠金额 -= MerPrin.IsFirstMon;
                        if (MerPrin.IsMaxPric > d_可算优惠金额)
                        {
                            goto addVal;
                        }
                        double d_不计入优惠金额 = i_总价 - d_可算优惠金额;
                        #region 优惠固定金额
                        if (MerPrin.MonType == 0)
                        {
                            i_优惠后总价 -= MerPrin.PricMon;
                        }
                        #endregion
                        #region 优惠百分比
                        else
                        {
                            double d_总价 = 0;//, d_菜品总价 = 0, d_包装总价 = i_打包费总价, d_配送费 = Mer.DelFormMon;
                            double pricmon = Convert.ToDouble(MerPrin.PricMon);
                            d_总价 = d_可算优惠金额 * (pricmon / 100.0) + d_不计入优惠金额;
                        //if (MerPrin.IsPackMon == 1)
                        //    {
                        //        d_包装总价 = i_打包费总价 * (pricmon / 1000.0);
                        //    }

                        //    d_菜品总价 = i_商品总价 * (pricmon / 1000.0);
                        //    if (MerPrin.IsFormMon == 1)
                        //    {
                        //        d_配送费 = Mer.DelFormMon * (pricmon / 1000.0);
                        //    }
                        //    d_总价 = d_菜品总价 + d_包装总价 + d_配送费;
                            switch (MerPrin.PricRem)
                            {
                                case 0:
                                    d_总价 = Math.Round(d_总价);
                                    break;
                                case 1:
                                    d_总价 = (int)d_总价;
                                    break;
                            }
                            i_优惠后总价 = d_总价;
                        }
                        #endregion
                    }
                    catch
                    {
                        goto addVal;
                    }
                
                   
                }
            addVal:
                OT.Total = i_优惠后总价.ToString();

                OT.Discount = (i_总价 - i_优惠后总价).ToString();
                if (IsTake == 2)
                {
                    OT.Total = (i_优惠后总价 - OT.DelFormMon).ToString();
                    OT.Discount = ((i_总价 - i_优惠后总价)).ToString();
                    OT.DelFormMon = 0;

                }
                result.BS = "1";
                result.Msg = "读取成功";
                result.rows = OT;
            }
            catch (Exception e)
            {
                result.BS = "-99";
                result.Msg = "系统异常";
                WriteLog.WriteW("CalcDiscount  " + e.Message);
            }

            return os.StringOfObject(result, RETID);
        }        
        #endregion
        /// <summary>
        /// 设置商户的对应订单优惠信息
        /// </summary>
        /// <param name="OperID">操作员ID</param>
        /// <param name="json">更新数据</param>
        /// <param name="tag">操作标签（1：新增；2：修改；3：删除）</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public string SetOrder_MerPricing(int OperID, string json, int tag, string YZM, int RETID)
        {
            WriteLog.WriteW("进入修改订单优惠    SetOrder_MerPricing(" + OperID + ",\"" + json + "\"," + tag + ",\"" + YZM + "\"," + RETID + ")");
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 执行操作
            try
            {
                Model.Order_MerPricing_T info = ParseClass<Model.Order_MerPricing_T>.StrDeserialize(json, RETID);
                string T = "";
                int ret = -1;
                // 根据操作标签Tag判断是什么操作
                switch (tag)
                {
                    case 1:
                        T = "新增";
                        if (base.GetListBy(u => u.PayID == info.PayID & u.MerID == info.MerID).Count > 0)
                        {
                            result.BS = "-99";
                            result.Msg = "更新失败,同一钱包不能重复";
                            return os.StringOfObject(result, RETID);
                        }
                        info.PricID = GetSysKey.GetKey("PicKey");
                        info.PricState = 1;
                        info.IsFormMon = 1;
                        info.IsPackMon = 1;
                        ret = base.Add(info);
                        break;
                    case 2:
                        T = "修改";
                        Model.Order_MerPricing_T tmp = base.GetListBy(u => u.PricID == info.PricID).First();
                        info.PricState = 1;
                        Help.FuZhi<Model.Order_MerPricing_T>.FZ(ref tmp, info);
                        ret = base.Modify(tmp);
                        break;
                    case 3:
                        T = "删除";
                        List<Model.Order_MerPricing_T> list_tmp = base.GetListBy(u => u.PricID == info.PricID);
                        if (list_tmp != null && list_tmp.Count > 0)
                        {
                            tmp = list_tmp.First();
                            tmp.PricState = 0;
                            ret = base.Modify(tmp);
                        }
                        break;
                }

                if (ret > 0)
                {
                    // 将操作记录到日志表中
                    Model.Order_OperationFlow_T Log = new Model.Order_OperationFlow_T();
                    Log.OperationTitle = "设置商户的对应订单优惠信息";
                    Log.OperationText = T + "商户的对应订单优惠信息成功";
                    Log.OperationType = "1F0006";
                    Log.OperationRes = "成功";
                    Log.OperationUser = OperID;
                    string str_log = os.StringOfObject(Log, RETID);
                    bool isSuccess = new Order_OperationFlow_T().AddOrder_OperationFlow(str_log, RETID);
                    if (!isSuccess)
                    {
                        WriteLog.WriteW("新增系统操作流水失败");
                    }
                    result.BS = "1";
                    result.Msg = "更新成功";
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "更新失败";
                }
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("更新商户的订单状态和备注信息失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "更新失败";
            }
            #endregion
            return os.StringOfObject(result, RETID);
        }

        /// <summary>
        /// 根据支付模式查询对应的支付信息
        /// </summary>
        /// <param name="PricType">支付模式(0：钱包，1：第三方)</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public string GetOrder_PayType(int PricType, string YZM, int RETID)
        {
            try
            {
                #region 匹配验证码
                if (YZM != Help.ALL_DataV.YZM)
                {
                    result.BS = "-88";
                    result.Msg = "验证码错误！";
                    return os.StringOfObject(result, RETID);
                }
                #endregion
                #region 执行操作
                List<Order_MerPricing_PayInfo> list = new List<Order_MerPricing_PayInfo>();

                if (PricType == 0)
                {
                    List<Model.Order_Walt_T> ls = bl.IOrder_Walt_TBLL.GetListBy(u => u.WaltState == 1);
                    if (ls != null && ls.Count > 0)
                    {
                        foreach (Model.Order_Walt_T item in ls)
                        {
                            Order_MerPricing_PayInfo info = new Order_MerPricing_PayInfo();
                            info.PayID = item.WaltID;
                            info.PayName = item.WaltName;
                            list.Add(info);
                        }
                    }
                }
                else if (PricType == 1)
                {
                    List<Model.Order_Pay_T> ls = bl.IOrder_Pay_TBLL.GetListBy(u => u.PayID == u.PayID);
                    if (ls != null && ls.Count > 0)
                    {
                        foreach (Model.Order_Pay_T item in ls)
                        {
                            Order_MerPricing_PayInfo info = new Order_MerPricing_PayInfo();
                            info.PayID = item.PayID;
                            info.PayName = item.PayName;
                            list.Add(info);
                        }
                    }
                }

                if (list != null & list.Count > 0)
                {
                    result.BS = "1";
                    result.Msg = "查询成功";
                    result.total = list.Count;
                    result.rows = list;
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "查询不到数据";
                }
                #endregion
                return os.StringOfObject(result, RETID);
            }
            catch (Exception ex)
            {
                WriteLog.WriteW(" 查询所有商户的评价管理信息失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "系统错误！";
                return os.StringOfObject(result, RETID);
            }
        }



        public class View_Order_MerPricing_More : Model.View_Order_MerPricing
        {
            public string PayName { get; set; }
        }

        public class Order_MerPricing_PayInfo
        {
            public string PayID { get; set; }
            public string PayName { get; set; }
        }
    }
}
